package com.terren.webdig.common.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

/**
 * 通用工具类
 * 
 */
public class CommonUtil {
	static Logger logger = LogManager.getLogger(CommonUtil.class);
	/**
	 * html字符串转义特殊字符 
	 * 
	 * @param message
	 *           
	 */
	public static String filter(String message) {

		if (message == null) {
			return (null);
		}
		char content[] = new char[message.length()];
		message.getChars(0, message.length(), content, 0);
		StringBuilder result = new StringBuilder(content.length + 50);
		for (int i = 0; i < content.length; i++) {
			switch (content[i]) {
			case '<':
				result.append("&lt;");
				break;
			case '>':
				result.append("&gt;");
				break;
			case '&':
				result.append("&amp;");
				break;
			case '"':
				result.append("&quot;");
				break;
			default:
				result.append(content[i]);
			}
		}
		return (result.toString());

	}

	/**
	 * 获得分页grid json
	 * 
	 * @param total
	 * @param itemList
	 * @return {total: 3,items: [{...}]}
	 */
	public static String getGridPageJson(int total, List<?> itemList) {
		Map<String, Object> gridDataMap = new HashMap<String, Object>();

		gridDataMap.put("total", total);
		gridDataMap.put("items", itemList);

		String resultJson = JSON.toJSONString(gridDataMap);
		return resultJson;
	}

	/**
	 * 获得datablesjson
	 * 
	 * @param total
	 * @param itemList
	 * @return {total: 3,items: [{...}]}
	 */
	public static String getDatablePageJson(int total, List<?> itemList) {
		Map<String, Object> gridDataMap = new HashMap<String, Object>();

		gridDataMap.put("recordsTotal", total);
		gridDataMap.put("recordsFiltered", total);
		gridDataMap.put("data", itemList);

		String resultJson = JSON.toJSONString(gridDataMap);
		return resultJson;
	}

	/**
	 * 返回ajax执行结果
	 * 
	 * @param isSuccess
	 * @param msg
	 * @return
	 */
	public static String returnAjaxJson(boolean isSuccess, String msg) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", isSuccess);
		resultMap.put("msg", msg);
		String json = JSON.toJSONString(resultMap);
		return json;
	}

	/**
	 * 返回ajax执行结果
	 * 
	 * @param isSuccess
	 * @param msg
	 * @return
	 */
	public static Map<String, Object> createAjaxMap(boolean isSuccess, String msg) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", isSuccess);
		resultMap.put("msg", msg);
		return resultMap;
	}

	public static String loginTimeOut() {
		String outJson = returnAjaxJson(false, "登录超时！");
		return outJson;
	}

	/**
	 * 拼接字符串
	 * 
	 * @param list
	 * @return
	 */
	public static String listToString(List<String> list) {
		StringBuilder builder = new StringBuilder();
		int i = 0;
		for (String oneText : list) {
			if (i > 0) {
				builder.append(",");
			}
			builder.append(oneText);
		}
		return builder.toString();
	}

	/**
	 * 转换IP地址
	 * 
	 * @param ip
	 * @return
	 */
	public static String getIpStringFromBytes(long ip) {
		StringBuilder sb = new StringBuilder();
		sb.append(ip >> 24);
		sb.append('.');
		sb.append(ip >> 16 & 0xFF);
		sb.append('.');
		sb.append(ip >> 8 & 0xFF);
		sb.append('.');
		sb.append(ip & 0xFF);
		return sb.toString();
	}

	/**
	 * ha1 加密
	 * 
	 * @param text
	 * @return
	 */
	public static String getHa1Encrypt(String text) {
		String result = DigestUtils.sha1Hex(text);
		return result;
	}

	/**
	 * 有些情况下ext treePanel node 会重复，为了防止重复，会添加 -xxx 样式的后缀，当使用该 node 时，需要去掉后缀 如
	 * 1-level1， 此 node 中 1 为真实node
	 * 
	 * @param nodeIdStr
	 * @return
	 */
	public static String clearNodeId(String nodeIdStr) {
		int index = nodeIdStr.indexOf("-");

		if (index > 0) {
			nodeIdStr = nodeIdStr.substring(0, index);
		}
		return nodeIdStr;
	}

	/**
	 * 字符串首字母大写
	 * 
	 * @param 字符串
	 * @return 首字母大写的字符串
	 */
	public static String toFirstUpperCase(String str) {
		if (str == null || str.length() < 1) {
			return "";
		}
		String start = str.substring(0, 1).toUpperCase();
		String end = str.substring(1, str.length());
		return start + end;
	}

	/**
	 * 获得随机数
	 * 
	 * @param minInt
	 * @param maxInt
	 * @return
	 */
	public static int getRandomInt(int minInt, int maxInt) {
		int number = maxInt - minInt + 1;

		Random random = new Random();

		int ranNum = random.nextInt(number) + minInt;// 0-5

		return ranNum;
	}

	/**
	 * 获得唯一ID
	 * 
	 * @return
	 */
	public static String getSingleId() {
		String formatType = "yyyyMMddHHmmsssss";
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat(formatType);

		String singleId = format.format(date);

		int ran = getRandomInt(0, 1000);

		singleId = singleId + "-" + ran;

		return singleId;
	}

	/**
	 * 获得登录用户 ip
	 * 
	 * @return
	 */
	public static String getLoginIp(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	/**
	 * 得到所有传递的参数以Map的形式保存
	 */
	public static Map<String, Object> getParameterMap(HttpServletRequest request) {
		Map<String, String[]> map = (Map<String, String[]>) request.getParameterMap();
		Map<String, Object> result = new HashMap<String, Object>();
		Set<Entry<String, String[]>> set = map.entrySet();
		StringBuffer params = new StringBuffer("params: ");
		for (Entry<String, String[]> entry : set) {
			String key = entry.getKey();
			String[] values = entry.getValue();
			String value = StringUtils.join(values, "-");
			result.put(key, value);
			params.append(key + "=" + value + " ");
		}
		logger.debug(params.toString());
		return result;
	}

	/**
	 * 得到所有传递的参数以Object的形式保存
	 */
	public static Object getParameterObject(Class<?> cls, HttpServletRequest request) {
		Object entity = null;
		try {
			entity = Class.forName(cls.getName()).newInstance();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		Map<String, String[]> map = (Map<String, String[]>) request.getParameterMap();
		Set<Entry<String, String[]>> set = map.entrySet();
		StringBuffer params = new StringBuffer();
		StringBuffer noParams = new StringBuffer();
		for (Entry<String, String[]> entry : set) {
			String key = entry.getKey();
			String[] values = entry.getValue();
			String value = StringUtils.join(values, "-");
			try {
				Class<?> type = cls.getMethod("get" + StringUtil.toFirstUpperCase(key)).getReturnType();
				if (null == type) {
					continue;
				}
				if (type.isEnum()) {
					type = String.class;
				}
				Method method = cls.getMethod("set" + StringUtil.toFirstUpperCase(key), type);
				method.invoke(entity, type.cast(StringUtil.castString(value, type)));
				params.append(key + "=" + value + " ");
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				noParams.append(key + "=" + value + " ");
				logger.debug("NoSuchMethod: " + key + "=" + value + " ");
				continue;
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		logger.debug("params: " + params.toString());
		if (noParams.toString().length() > 0) {
			logger.warn("no params: " + noParams.toString());
		}
		return entity;
	}
}
